package com.hcb.tonguetiphealth.widget.drinksbook;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;

import com.hcb.tonguetiphealth.adapter.DrinksBookDialogListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.manager.WineManager;
import com.hcb.tonguetiphealth.model.Wine;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class DrinksBookDialog extends GeneralWidget {
	private static final String TAG = "DrinksBookDialog";
	private String URL;
	private String url_wineBrands = Global.URL + Global.servlet_wineBrands;
	private String url_wineTypes = Global.URL + Global.servlet_wineTypes;
	private String url_winePrice = Global.URL + Global.servlet_winePrice;
	private Activity ctx;
	private Handler handler;
	private WineManager wineManager;
	private static DrinksBookDialogListAdapter adapter;
	private ProgressBar progressBar;
	private ListView listView;
	private Handler mHandler;
	private PopupWindow window;
	private List<Wine> wineList;
	private Wine wine;
	private int flag;
	private boolean needSave = true;
	
	public DrinksBookDialog(Context context) {
		super(context);
		ctx = (Activity)context;
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在获取酒水列表...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					progressBar.setVisibility(ProgressBar.GONE);
					//adapter.notifyDataSetChanged();
					adapter = new DrinksBookDialogListAdapter(ctx, wineList);
			        listView.setAdapter(adapter);
			        listView.setOnItemClickListener(new OnItemClickListener() {
						public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
							// TODO Auto-generated method stub
							Wine result = (Wine)arg0.getAdapter().getItem(arg2);
							
							if(null != mHandler) {
								Message msg = mHandler.obtainMessage(flag, result);  
								mHandler.sendMessage(msg); 
							}
							
							window.dismiss();
						}
					});
					if(needSave) {
						dismissMessageDialog();
						if(wineList.size() > 0) {
							wineManager.saveWine(wineList);
						}
					}
					break;
				}
			}
		};
	}
	//创建一个包含自定义view的PopupWindow
	public PopupWindow makePopupWindow(View tagView, final int flag, final Handler mHandler) {
		this.flag = flag;
		this.mHandler = mHandler;
		wineManager = new WineManager(ctx, flag);
	    window = new PopupWindow(ctx);
	    
	    LayoutInflater li = LayoutInflater.from(ctx); 
        View view = li.inflate(R.layout.drinks_book_dialog_list, null); 
        progressBar = (ProgressBar)view.findViewById(R.id.drinks_book_dialog_progressbar);
        progressBar.setVisibility(ProgressBar.VISIBLE);
        listView = (ListView)view.findViewById(R.id.drinks_book_dialog_listview);
        initData();
	    
	    final Resources res = ctx.getResources();
	    view.setBackgroundColor(res.getColor(R.color.transparent2));
	    view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
	            LayoutParams.WRAP_CONTENT));
	    //设置PopupWindow显示和隐藏时的动画
	    window.setAnimationStyle(R.style.AnimationFade);
	    //设置PopupWindow的大小（宽度和高度）
	    int width = 0;
	    if(flag == Wine.PRICE || flag == Wine.BRAND ) {
	    	width = tagView.getWidth() * 2;
	    } else {
	    	width = tagView.getWidth();
	    }
	    window.setWidth(width);
	    window.setHeight(LayoutParams.WRAP_CONTENT);
	    //window.setWidth(res.getDimensionPixelSize(R.dimen.page_window_width));
	    //window.setHeight(res.getDimensionPixelSize(R.dimen.page_window_height));
	    //设置PopupWindow的内容view
	    window.setContentView(view);
        //设置PopupWindow外部区域是否可触摸
        window.setOutsideTouchable(true);
        //设置焦点，必须设置，否则listView无法响应
        window.setFocusable(true);
        window.update();
        
	    return window;
	}
	
	private void initData() {
		wineList = new ArrayList<Wine>();
		switch(flag) {
		case Wine.BRAND:
			if(WineManager.isGotBrad) {
				needSave = false;
				wineList = wineManager.getWineList();
				handler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			} else {
				URL = url_wineBrands;
				initWineList();
			}
			break;
		case Wine.PRICE:
			if(WineManager.isGotPrice) {
				needSave = false;
				wineList = wineManager.getWineList();
				handler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			} else {
				URL = url_winePrice;
				initWineList();
			}
			break;
		case Wine.TYPE:
			if(WineManager.isGotType) {
				needSave = false;
				wineList = wineManager.getWineList();
				handler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			} else {
				URL = url_wineTypes;
				initWineList();
			}
			break;
		case Wine.POPULARITY:
			wineList.clear();
			wine = new Wine();
			wine.setStrId("0");
			wine.setName("降序");
			wineList.add(wine);
			wine = new Wine();
			wine.setStrId("1");
			wine.setName("升序");
			wineList.add(wine);
			handler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			break;
		}
	}
	private void initWineList() {
		new Thread() {
			public void run() {
				String response = null;
				try {
					response = HttpUtils.doGet(URL);
				} catch (ClientProtocolException e) {
					Log.e(TAG, "ClientProtocolException", e);
				} catch (IOException e) {
					Log.e(TAG, "IOException", e);
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						JSONArray jList = jManager.getJsonList();
						if(null == jList) {
							wineList = wineManager.getWineList();
						} else {
							wineList.clear();
							wine = new Wine();
							wine.setStrId("-1");
							wine.setName("全部");
							wineList.add(wine);
							for(int i=0; i< jList.length(); i++) {
								JSONObject jObject = getJSONObject(jList, i);
								if(null != jObject) {
									wine = new Wine();
									wine.setStrId(getString(jObject, "catid"));
									wine.setName(getString(jObject, "catname"));
									wineList.add(wine);
								}
							}
							needSave = true;
						}
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					} else {
						wineList = wineManager.getWineList();
					}
				} else {
					wineList = wineManager.getWineList();
				}
				handler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}

	@Override
	public void notifyAdapter() {
		// TODO Auto-generated method stub
		
	}
}
